package com.qf.filter;


import com.qf.fronted.dao.OrderDao;
import com.qf.fronted.dao.impl.OrderDaoImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@WebFilter("/*")
public class CalculateOrderTimeFilter implements Filter {

    private OrderDao orderDao = new OrderDaoImpl();
    private ScheduledExecutorService service = Executors.newScheduledThreadPool(10);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        CalculateOrderTime();
    }

    /**
     * 延迟执行
     *
     */
    private void CalculateOrderTime() {

        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                orderDao.CalculateOrderTime(service);
            }
        },1,1, TimeUnit.SECONDS);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        service.shutdown();
    }
}
